<template>
  <div>
    <el-row :gutter="10" class="linkShowSearchCondition">
      <el-col :span="6" style="width:350px;">
        <div :class="lang === 'zh'?'showZh':'showEn'">{{$t('起始日期：')}}</div>
        <el-date-picker v-model="record.startTime" clearable type="datetime" style="margin-bottom:10px;" value-format='yyyy-MM-dd HH:mm:ss' :picker-options="startDatePickerOptions" :default-value="defaultStartTime()" size='small' :placeholder="$t('选择起始日期时间')">
        </el-date-picker>
      </el-col>
      <el-col :span="6" style="width:350px;">
        <div :class="lang === 'zh'?'showZh':'showEn'">{{$t('结束日期：')}}</div>
        <el-date-picker v-model="record.endTime" clearable type="datetime" style="margin-bottom:10px;" value-format='yyyy-MM-dd HH:mm:ss' :picker-options="endDatePickerOptions" :default-value="defaultEndTime()" size='small' :placeholder="$t('选择结束日期时间')">
        </el-date-picker>
      </el-col>
      <el-col :span="6" style="width:350px;">
        <div :class="lang === 'zh'?'showZh':'showEn'">{{$t('所属模块：')}}</div>
        <el-select v-model="record.mode" ref="mode" filterable clearable :placeholder="$t('请选择')" style="width:220px;margin-bottom:10px;" size='small'>
          <el-option v-for="item in modesList" :key="item.name" :label="$t(item.chinese_name)" :value="item.name">
          </el-option>
        </el-select>
      </el-col>
      <el-col :span="6" style="width:350px;">
        <div :class="lang === 'zh'?'showZh':'showEn'">{{$t('日志级别：')}}</div>
        <el-select v-model="record.level" ref="level" filterable clearable :placeholder="$t('请选择')" style="width:220px;margin-bottom:10px;" size='small'>
          <el-option v-for="(item, key) in levelList" :key="key" :label="item" :value="key">
          </el-option>
        </el-select>
      </el-col>
      <el-col :span="6" style="width:350px;">
        <div :class="lang === 'zh'?'showZh':'showEn'">{{$t('源地址：')}}</div>
        <el-input v-emoji v-model="record.srcIp" ref="srcIp" style="width:220px;margin-bottom:10px;" size='small'></el-input>
      </el-col>
    </el-row>
    <div class="AuxiliarybuttonBox">
      <el-button type="success" size='small' @click="listData('init')" class="search">{{$t('搜索')}}</el-button>
      <el-button type="danger" size='small' @click="clearListData" class="clearList">{{$t('清空日志')}}</el-button>
      <el-button type="success" size='small' @click="exportSearchData()" class="exportSearch">{{$t('导出日志')}}</el-button>
    </div>
    <el-table ref="multipleTable" size='mini' :data="tableList" @sort-change='sortChange' tooltip-effect="dark" style="width: 100%">
      <el-table-column prop="TIME" align='center' :label="$t('时间')" sortable='custom' :formatter="timeFormatter" min-width="150"></el-table-column>
      <el-table-column prop="MODE" align='center' :label="$t('模块')" min-width="120">
        <template slot-scope="scope">
          {{ $t(modeListShow(scope.row.MODE)) || '' }}
        </template>
      </el-table-column>
      <el-table-column prop="LEVEL" align='center' sortable='custom' :label="$t('级别')" min-width="80">
        <template slot-scope="scope">
          {{ levelList[scope.row.LEVEL] || '' }}
        </template>
      </el-table-column>
      <el-table-column prop="MSG" align='center' :label="$t('信息')" min-width="400">
        <template slot-scope="scope">
          <tooltip :copyText="scope.row.MSG" class="wid190">
          </tooltip>
        </template>
      </el-table-column>
      <el-table-column prop="SIP" align='center' :label="$t('源地址')" min-width="150">
        <template slot-scope="scope">
          <tooltip :copyText="scope.row.SIP" class="wid190">
          </tooltip>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="record.page" :page-size="record.limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
    </el-pagination>

    <save-dialog v-if="saveDialogVisible" ref="refSaveDialogVisible"></save-dialog>
  </div>
</template>

<script>
import { searchMgmtLog, cleanMgmtLog, getMgmtMode } from '@/api/system/log'
import SaveDialog from './components/SaveDialog.vue'
import moment from 'moment'
import { inputClass, selectClass } from '@/utils/input-class.js'
import { getTime } from '@/api/home'
export default {
  name: 'Managelog',
  components: {
    SaveDialog
  },
  data () {
    return {
      saveDialogVisible: false,
      record: {
        mode: '',
        level: '',
        startTime: '',
        endTime: '',
        srcIp: '',
        sort: '',
        order: '',
        page: 1,
        limit: 20
      },
      recordCopy: {
        mode: '',
        level: '',
        startTime: '',
        endTime: '',
        srcIp: '',
        sort: '',
        order: '',
        page: 1,
        limit: 20
      },
      form: {
        mode: '',
        level: '',
        startTime: '',
        endTime: '',
        srcIp: '',
        sort: '',
        order: '',
        page: 1,
        limit: 20
      },
      lang: this.$i18n.locale,
      total: 0,
      tableList: [],
      levelList: {
        '1': 'ERROR',
        '2': 'ALERT',
        '3': 'INFO',
        '4': 'DEBUG'
      },
      sortList: {
        'descending': 'desc',
        'ascending': 'asc'
      },
      modesList: null,
      startDatePickerOptions: {
        disabledDate: (time) => {
          if (this.record.endTime) {
            return time > new Date(this.record.endTime).getTime()
          }
        }
      },
      endDatePickerOptions: {
        disabledDate: (time) => {
          if (this.record.startTime) {
            return time <= (new Date(this.record.startTime).getTime() - (24 * 60 * 60 * 1000))
          }
        }
      }
    }
  },
  created () {
    getTime()
    this.listData('init')
    getMgmtMode().then(res => {
      if (res.status === 0) {
        this.modesList = []
        for (let item of res.info) {
          if (!item.log || item.log !== 'off') {
            this.modesList.push({
              chinese_name: item.chinese_name,
              name: item.name
            })
          }
        }
      }
    })
  },
  mounted () {
    this.$nextTick(() => {
      const data = ['srcIp']
      const selectData = ['level', 'mode']
      inputClass(this.$refs, data)
      selectClass(this.$refs, selectData)
    })
  },
  methods: {
    handleSizeChange (val) {
      // console.log(`每页 ${val} 条`)
      this.record.limit = val
      this.form.limit = val
      this.record.page = 1
      this.form.page = 1
      this.listData()
    },
    handleCurrentChange (val) {
      // console.log(`当前页: ${val}`)
      this.record.page = val
      this.form.page = val
      this.listData()
    },
    listData (data) {
      let formData = JSON.parse(JSON.stringify(this.form))
      if (data === 'init') {
        this.record.page = 1
        this.form = JSON.parse(JSON.stringify(this.record))
        formData = JSON.parse(JSON.stringify(this.record))
      }
      if (formData.srcIp && this.validateIp(formData.srcIp)) {
        this.$messages.error('源地址格式错误')
      } else {
        searchMgmtLog(formData).then(res => {
          if (res.status === 0) {
            this.tableList = res.info.data
            this.total = res.info.count
          }
        })
      }
    },
    defaultEndTime () {
      if (this.record.startTime && new Date(this.record.startTime).getTime() > new Date().getTime()) {
        return this.record.startTime
      } else {
        return new Date()
      }
    },
    defaultStartTime () {
      if (this.record.endTime && new Date(this.record.endTime).getTime() < new Date().getTime()) {
        return this.record.endTime
      } else {
        return new Date()
      }
    },
    validateIp (value) {
      let ipv4 = /^((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})(\.((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})){3}$/
      let ipv6 = /^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/
      if (ipv4.test(value) || ipv6.test(value)) {
        return false
      } else {
        return '请输入正确的地址'
      }
    },
    dialogVisible () {
      this.saveDialogVisible = true
      this.$nextTick(() => {
        this.$refs.refSaveDialogVisible.init()
      })
    },
    clearListData () {
      this.$confirm(this.$t('确定清空日志吗,清空日志需要一定时间！'), this.$t('提示'), {
        closeOnClickModal: false,
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        confirmButtonClass: 'confirmButton',
        cancelButtonClass: 'confirmCancelButton',
        type: 'warning'
      }).then(() => {
        cleanMgmtLog().then(res => {
          if (res.status === 0) {
            this.$message({
              message: this.$t('清空成功'),
              type: 'success'
            })
            this.listData('init')
          }
        })
      })
    },
    sortChange (column, prop, order) {
      if (column.order) {
        this.record.sort = column.prop
        this.form.sort = column.prop
        this.record.order = this.sortList[column.order]
        this.form.order = this.sortList[column.order]
      } else {
        this.record.sort = ''
        this.record.order = ''
        this.form.sort = ''
        this.form.order = ''
      }
      this.listData()
    },
    exportSearchData () {
      this.saveDialogVisible = true
      this.$nextTick(() => {
        this.$refs.refSaveDialogVisible.init(this.record)
      })
    },
    timeFormatter (data) {
      return moment(new Date(data.TIME * 1000)).format('YYYY-MM-DD HH:mm:ss')
    },
    modeListShow (mode) {
      if (this.modesList) {
        return this.modesList.filter(item => item.name === mode)[0] ? this.modesList.filter(item => item.name === mode)[0].chinese_name : ''
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.showZh {
  width: 70px;
  display: inline-block;
}
.showEn {
  width: 105px;
  display: inline-block;
}
</style>
